# -*- coding: utf-8 -*-
import random
import scrapy
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from zc_core.util.http_util import retry_request
from zc_core.dao.order_pool_dao import OrderPoolDao
from zc_core.model.items import Box, OrderStatus
from henan.items import HenanOrderItem, NoMatchOrderItem
from henan.utils.order_helper import OrderHelper
from henan.rules import *
from zc_core.spiders.base import BaseSpider


class OrderItemSpider(BaseSpider):
    name = 'order_item'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderItemSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        self.order_helper = OrderHelper()

    def start_requests(self):
        # 处理订单列表
        order_list = OrderPoolDao().get_todo_list(self.batch_no, fields={'_id': 1, 'url': 1, 'orderTime': 1})
        if order_list:
            self.logger.info('目标: count=%s' % (len(order_list)))
            random.shuffle(order_list)
            for order in order_list:
                order_id = order.get('_id')
                order_url = order.get('url')
                order_time = order.get('orderTime')

                yield Request(
                    url=order_url,
                    meta={
                        'reqType': 'order_item',
                        'orderId': order_id,
                        'orderTime': order_time,
                    },
                    headers={
                        'Connection': 'keep-alive',
                        'Cache-Control': 'max-age=0',
                        'Upgrade-Insecure-Requests': '1',
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400',
                        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                        'Accept-Encoding': 'gzip, deflate',
                        'Accept-Language': 'zh-CN,zh;q=0.9',
                    },
                    callback=self.parse_order_item,
                    errback=self.error_back,
                    priority=1000,
                )

    def parse_order_item(self, response):
        meta = response.meta
        order_id = meta.get('orderId')
        order_time = meta.get('orderTime')
        item_list = parse_order_item(response)
        if item_list:
            to_save_list = list()
            self.logger.info('清单: order=%s, cnt=%s' % (order_id, len(item_list)))
            for order_item in item_list:
                sku_name = order_item.get('skuName')
                sp_name = order_item.get('supplierName')
                # 特殊处理
                if sp_name == '欧菲斯办公伙伴控股有限公司':
                    sp_name = '欧菲斯办公伙伴河南贸易有限公司'
                sku_id = self.order_helper.find_sku_id(sp_name, sku_name)
                sp_id = self.order_helper.find_supplier_id(sp_name)

                if sku_id and sp_id:
                    order_item.pop('unitPrice', None)
                    order_item.pop('catalogBrand', None)
                    order_item['skuId'] = sku_id
                    order_item['supplierId'] = sp_id
                    item = HenanOrderItem()
                    item.update(order_item)
                    self.logger.info('明细: id=%s' % (item.get('id')))
                    to_save_list.append(item)
                    # yield item
                else:
                    spu_id = self.order_helper.find_spu_id(sku_name)
                    if spu_id and sp_id:
                        # 构造商品池
                        # new_sku = copy.copy(spu_id)
                        # new_sku['supplierId'] = sp_id
                        # new_sku['supplierName'] = sp_name
                        # new_sku['supplierSkuId'] = ''
                        # new_sku['supplierSkuLink'] = ''
                        # new_sku['salePrice'] = order_item.pop('unitPrice')
                        # new_sku['originPrice'] = new_sku['salePrice']
                        # new_sku['batchNo'] = self.batch_no
                        # new_sku['skuId'] = md5(new_sku.get('spuId') + '_' + sp_id)
                        # new_sku['_id'] = new_sku['skuId']
                        # # 补充批次商品
                        # item_data = ItemData()
                        # item_data.update(new_sku)
                        # yield item_data
                        # # 补充商品池
                        # pool_item = ItemPoolData()
                        # pool_item.update(new_sku)
                        # yield pool_item
                        self.logger.info(
                            '映射失败[补充商品]: sp=%s, sku=%s, spuId=%s, url=%s' % (sp_name, sku_name, spu_id, response.url))
                    elif not spu_id:
                        self.logger.error('映射失败[无同款]: sp=%s, sku=%s, url=%s' % (sp_name, sku_name, response.url))
                    elif not sp_id:
                        self.logger.error('映射失败[无供应商]: sp=%s, sku=%s, url=%s' % (sp_name, sku_name, response.url))

                    no_match_item = NoMatchOrderItem()
                    no_match_item.update(order_item)
                    yield no_match_item

            # 保存订单明细
            if to_save_list:
                yield Box('order_item', self.batch_no, to_save_list)
            # 标记订单已采
            if len(to_save_list) == len(item_list):
                order_status = OrderStatus()
                order_status['id'] = order_id
                order_status['orderTime'] = order_time
                order_status['batchNo'] = time_to_batch_no(order_time)
                order_status['workStatus'] = 1
                yield order_status
        else:
            self.logger.info('无明细: order=%s' % order_id)
